package cn.xiaobai;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.time.Instant;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author yangdaji
 * @Date 2024/2/22
 * @PackageName ${PACKAGE_NAME}
 * @ClassName ${NAME}
 */
public class JWTTest {
    public static void main(String[] args) {

        String token = createToken();
        System.out.println(token);

        verification(token);
    }

    /**
     * 生成 token
     *
     * @return
     */
    public static String createToken() {
        Calendar instance = Calendar.getInstance();
        // 默认30 s
        instance.add(Calendar.SECOND, 30);

        // 头部map
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("typ", "jwt");
        headerMap.put("alg", "sha256");

        return JWT.create()
                .withHeader(headerMap)      // 头部, 默认使用 sha256 算法
                .withIssuer("xiao yang")    // 签发者
                .withIssuedAt(Instant.now())  // 签发时间
                .withExpiresAt(instance.getTime())        // 有效时间
                .withSubject("daji_yang@163.com")   // 面向用户
                .withAudience("www.baidu.com","www.google.com")  // 接收方
                .withNotBefore(Instant.now())           // 定义某个时间前都不可用
                .withJWTId("dddddddd")      // 唯一身份标识
                .withClaim("userId", 11)     // palyload
                .withClaim("username", "guest") // palyload
                .sign(Algorithm.HMAC256("xiaobai"));
    }

    /**
     * 验证 token
     *
     * @param token
     */
    public static void verification(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256("xiaobai")).build();
        DecodedJWT decodedJWT = verifier.verify(token);

        System.out.println(decodedJWT.getClaim("userId"));
        System.out.println(decodedJWT.getClaim("username"));
    }
}